# -*- coding: UTF-8 -*-
"""
    TweMoi, aplicación Android para la interacción con redes sociales
    Copyright (C) 2011
        * Autor: Moisés Vázquez Sánchez
        * Tutor: Jesús M. González Barahona
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import os
import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import models

class Amigos(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        if (not(user)):
            self.redirect("/", True)
        
        user_query = models.Usuario.all().filter('user_twemoi = ', user.nickname())
        if (user_query.get() != None):
            usuario = user_query.get()
        else:
            usuario = None

        
        list_amigos = models.Amigo.all().filter('user_twemoi = ', user.nickname())
           
        template_values = {
                           'user' : usuario,
                           'red' : "twitter",
                           'amigos' : list_amigos,
                           'num_amigos' : list_amigos.count(),
                           'link_salir' : users.create_logout_url("/")
                           }

        path = os.path.join(os.path.dirname(__file__), 'gestion_amigos.html')
        self.response.out.write(template.render(path, template_values))

class Agregar_amigo(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        
        if (not(user)):
            self.redirect("/", True)

        path = os.path.join(os.path.dirname(__file__), 'form_amigo.html')
        self.response.out.write(template.render(path, {}))

        
    def post(self):
        
        nombre_amigo = cgi.escape(self.request.get('nombre_amigo'))
        
        query = models.Usuario.all().filter('user_twemoi=', nombre_amigo)
        results = query.get()
        if (results == None):
            self.response.out.write("El usuario no se encuentra en la aplicacion")
            return
        
        user = users.get_current_user()
        if user:        
            amigo = models.Amigo()
            amigo.author = user
            amigo.user_twemoi = user.nickname()
            amigo.nombre_amigo = nombre_amigo
            amigo.put()
            self.response.out.write("Anadido correctamente")
        else:
            self.redirect("/", True)

class Conocer_amigo(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        
        query = models.Amigo.all().filter('user_twemoi = ', user.nickname())
        
        amigos = query.get()
        if (amigos == None):
            self.response.out.write("No tiene amigos agregados a la red de Twemoi")
            return
        
        for amigo in query:
            query_User = models.Usuario.all().filter('user_twemoi =', amigo.nombre_amigo)
            if (query_User.get() != None):
                query_red = models.Red.all().filter('user_twemoi =', amigo.nombre_amigo)
                
                for conocido in query_red:
                    self.response.out.write("Conoces a " + amigo.nombre_amigo + " tambien se encuentra en: " + conocido.tipo_red + " con el nombre de usuario de: " + conocido.user_red)

        self.response.out.write("Fin de conocer!")

application = webapp.WSGIApplication(
                                     [('/amigos', Amigos),
                                      ('/amigos/agregar', Agregar_amigo),
                                      ('/amigos/conocer', Conocer_amigo)
                                      ],debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
